#include "sdk.h"
#include <wx/filedlg.h>
#include "editpairdlg.h"
#include "filefilters.h"

static const wxRegEx reKey( _T( "^[[:alnum:]_]+$" ), wxRE_EXTENDED );

BEGIN_EVENT_TABLE( EditPairDlg, wxScrollingDialog )
  EVT_BUTTON( XRCID( "btnBrowse" ), EditPairDlg::OnBrowse )
  EVT_UPDATE_UI( -1, EditPairDlg::OnUpdateUI )
END_EVENT_TABLE()

EditPairDlg::EditPairDlg( wxWindow* parent, wxString& key, wxString& value, const wxString& title, BrowseMode allowBrowse ) : m_Key( key ), m_Value( value ), m_BrowseMode( allowBrowse ) {
  wxXmlResource* xml_res = wxXmlResource::Get();
  wxString resPath = ConfigManager::GetDataFolder() + _T( "/edit_pair.xrc" ) ;
  xml_res->Load( resPath );
  if( !xml_res->LoadObject( this, parent, _T( "dlgEditPair" ), _T( "wxScrollingDialog" ) ) ) {
    return;
  }
  XRCCTRL( *this, "wxID_OK", wxButton )->SetDefault();
  SetTitle( title );
  XRCCTRL( *this, "btnBrowse", wxButton )->Enable( m_BrowseMode != bmDisable );
  XRCCTRL( *this, "txtKey", wxTextCtrl )->SetValue( key );
  XRCCTRL( *this, "txtValue", wxTextCtrl )->SetValue( value );
}

EditPairDlg::~EditPairDlg() {
}

void EditPairDlg::OnUpdateUI( M_Code_unused wxUpdateUIEvent& event ) {
  const wxString &value = XRCCTRL( *this, "txtKey", wxTextCtrl )->GetValue();
  bool enable = !value.IsEmpty();
  if( enable ) {
    enable = reKey.Matches( value );
  }
  XRCCTRL( *this, "wxID_OK", wxButton )->Enable( enable );
}

void EditPairDlg::OnBrowse( M_Code_unused wxCommandEvent& event ) {
  switch( m_BrowseMode ) {
    case bmBrowseForFile: {
      wxFileDialog dlg( this,
                        _T( "Select file" ),
                        XRCCTRL( *this, "txtValue", wxTextCtrl )->GetValue(),
                        _T( "" ),
                        FileFilters::GetFilterAll(),
                        wxFD_OPEN | compatibility::wxHideReadonly );
      PlaceWindow( &dlg );
      if( dlg.ShowModal() == wxID_OK ) {
        XRCCTRL( *this, "txtValue", wxTextCtrl )->SetValue( dlg.GetPath() );
      }
      break;
    }
    case bmBrowseForDirectory: {
      wxString dir = ChooseDirectory( this,
                                      _T( "Select directory" ),
                                      XRCCTRL( *this, "txtValue", wxTextCtrl )->GetValue(),
                                      _T( "" ),
                                      false,
                                      true );
      if( !dir.IsEmpty() ) {
        XRCCTRL( *this, "txtValue", wxTextCtrl )->SetValue( dir );
      }
      break;
    }
    case bmDisable:
    default:
      break;
  }
}

void EditPairDlg::EndModal( int retCode ) {
  if( retCode == wxID_OK ) {
    m_Key = XRCCTRL( *this, "txtKey", wxTextCtrl )->GetValue();
    m_Value = XRCCTRL( *this, "txtValue", wxTextCtrl )->GetValue();
  }
  wxScrollingDialog::EndModal( retCode );
}
